﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using System.Web.Script.Serialization;

namespace PortUsedKill.Utils
{
    public class HttpHelper
    {
        public static T GetHttpResponse<T>(string url, int timeout)
        {
            string res = GetHttpResponse(url, timeout);
            JavaScriptSerializer js = new JavaScriptSerializer();
            T t = js.Deserialize<T>(res);
            return t;
        }
        ///
        /// Get请求
        /// 
        /// 
        /// 字符串
        public static string GetHttpResponse(string url, int timeout)
        {
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
            request.Method = "GET";
            request.ContentType = "text/html;charset=UTF-8";
            request.UserAgent = null;
            request.Timeout = timeout;

            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            Stream responseStream = response.GetResponseStream();
            string encoding = response.CharacterSet;
            StreamReader streamReader = null;
            switch (encoding)
            {
                case "GBK":
                    streamReader = new StreamReader(responseStream, Encoding.GetEncoding("GBK"));
                    break;
                case "utf-8":
                    streamReader = new StreamReader(responseStream, Encoding.UTF8);
                    break;
                default:
                    streamReader = new StreamReader(responseStream, Encoding.Default);
                    break;
            }
            string retString = streamReader.ReadToEnd();
            streamReader.Close();
            responseStream.Close();

            return retString;
        }


    }
}
